package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.user.dto.LoginDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.awt.geom.QuadCurve2D;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-11-13
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {

        //判断手机号和密码不能为空
        if (StringUtils.isNotBlank (dto.getPhone ())&& StringUtils.isNotBlank (dto.getPassword ())){
            //1.手机号和密码登录
            //根据手机号查询用户’
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<> ();
            queryWrapper.eq (ApUser::getPhone,dto.getPhone ());
            ApUser one = this.getOne (queryWrapper);
            if (one==null){
                return ResponseResult.errorResult (AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //判断密码是否正确
            String password = DigestUtils.md5Hex (dto.getPassword () + one.getSalt ());
            String password1 = one.getPassword ();
            if (!StringUtils.equals (password,password1)){
                return ResponseResult.errorResult (AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //返回结果
            Map resultMap = new HashMap ();
            one.setPassword ("");
            one.setSalt ("");
            resultMap.put ("user",one);

            Map claimMaps=new HashMap ();
            claimMaps.put ("userId",one.getId ());
            claimMaps.put ("name",one.getName ());
            String token = AppJwtUtil.getToken (claimMaps);
            resultMap.put ("token",token);

            return ResponseResult.okResult (resultMap);
        }else {

            //2.不登陆 游客访问
            //返回结果
            ApUser one = new ApUser ();
            Map resultMap = new HashMap ();
            one.setId (0);
            resultMap.put ("user",one);

            Map claimMaps=new HashMap ();
            claimMaps.put ("userId",0);
            claimMaps.put ("name",dto.getEquipmentId ());
            String token = AppJwtUtil.getToken (claimMaps);
            resultMap.put ("token",token);

            return ResponseResult.okResult (resultMap);
        }
    }
}
